<template>
  <view class="community-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <text class="title">社区</text>
        <!-- 添加搜索框 -->
        <view class="search-box" @tap="goSearch">
          <uni-icons type="search" size="16" color="#999"></uni-icons>
          <text class="placeholder">搜索帖子</text>
        </view>
        <view class="post-btn" @tap="goPost">
          <uni-icons type="plusempty" size="24" color="#333"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 帖子列表 -->
    <scroll-view 
      class="content-scroll" 
      scroll-y 
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
      refresher-enabled
      :refresher-triggered="isRefreshing"
    >
      <view class="waterfall-container">
        <!-- 左列 -->
        <view class="waterfall-column">
          <view 
            class="post-item"
            v-for="post in leftPosts"
            :key="post.id"
            @tap="goDetail(post)"
          >
            <!-- 图片展示（只显示第一张） -->
            <view class="image-wrap" v-if="post.images && post.images.length > 0">
              <image 
                :src="post.images[0]"
                mode="widthFix"
                class="post-image"
                @load="onImageLoad(post.id, $event)"
              ></image>
              <!-- 多图标识 -->
              <view class="image-count" v-if="post.images.length > 1">
                <uni-icons type="images" size="16" color="#fff"></uni-icons>
              </view>
            </view>
            
            <!-- 帖子内容 -->
            <view class="post-content">
              <text class="title">{{ post.title }}</text>
            </view>
            
            <!-- 底部信息栏 -->
            <view class="post-footer">
              <!-- 用户信息 -->
              <view class="user-info" @tap.stop="goUserSpace(post)">
                <image class="avatar" :src="post.userAvatar || '/static/images/default-avatar.jpg'" mode="aspectFill"></image>
                <text class="nickname">{{ post.userNickname }}</text>
              </view>
              <!-- 点赞信息 -->
              <view class="like-info" @tap.stop="handleLike(post)">
                <uni-icons :type="post.isLiked ? 'heart-filled' : 'heart'" size="18" :color="post.isLiked ? '#ff4757' : '#999'"></uni-icons>
                <text :class="{ active: post.isLiked }">{{ post.likeCount }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 右列 -->
        <view class="waterfall-column">
          <view 
            class="post-item"
            v-for="post in rightPosts"
            :key="post.id"
            @tap="goDetail(post)"
          >
            <!-- 图片展示（只显示第一张） -->
            <view class="image-wrap" v-if="post.images && post.images.length > 0">
              <image 
                :src="post.images[0]"
                mode="widthFix"
                class="post-image"
                @load="onImageLoad(post.id, $event)"
              ></image>
              <!-- 多图标识 -->
              <view class="image-count" v-if="post.images.length > 1">
                <uni-icons type="images" size="16" color="#fff"></uni-icons>
              </view>
            </view>
            
            <!-- 帖子内容 -->
            <view class="post-content">
              <text class="title">{{ post.title }}</text>
            </view>
            
            <!-- 底部信息栏 -->
            <view class="post-footer">
              <!-- 用户信息 -->
              <view class="user-info" @tap.stop="goUserSpace(post)">
                <image class="avatar" :src="post.userAvatar || '/static/images/default-avatar.jpg'" mode="aspectFill"></image>
                <text class="nickname">{{ post.userNickname }}</text>
              </view>
              <!-- 点赞信息 -->
              <view class="like-info" @tap.stop="handleLike(post)">
                <uni-icons :type="post.isLiked ? 'heart-filled' : 'heart'" size="18" :color="post.isLiked ? '#ff4757' : '#999'"></uni-icons>
                <text :class="{ active: post.isLiked }">{{ post.likeCount }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <uni-load-more :status="loadMoreStatus"></uni-load-more>
    </scroll-view>
  </view>
</template>

<script>
import { isLoggedIn } from '@/utils/auth'

export default {
  data() {
    return {
      posts: [],
      leftPosts: [],
      rightPosts: [],
      page: 1,
      pageSize: 10,
      loadMoreStatus: 'more',
      isRefreshing: false,
      leftHeight: 0,
      rightHeight: 0,
      screenWidth: 0,
      columnWidth: 0,
      columnGap: 16
    }
  },
  
  onLoad() {
    // 获取屏幕宽度
    const systemInfo = uni.getSystemInfoSync()
    this.screenWidth = systemInfo.windowWidth
    // 计算列宽 (屏幕宽度 - 外边距 - 列间距) / 2
    this.columnWidth = (this.screenWidth - 32 - this.columnGap) / 2
    this.loadPosts()
  },
  
  methods: {
    // 加载帖子列表
    async loadPosts() {
      try {
        if (this.page === 1) {
          this.posts = []
          this.leftPosts = []
          this.rightPosts = []
          this.leftHeight = 0
          this.rightHeight = 0
        }
        
        this.loadMoreStatus = 'loading'
        
        const params = {
          pageNum: this.page,
          pageSize: this.pageSize
        }
        
        const res = await this.$api.community.posts.list(params)
        if (res.code !== 200) {
          throw new Error(res.message || '加载失败')
        }
        
        const { data } = res
        
        // 处理数据，设置默认值
        const formattedPosts = data.records.map(post => ({
          ...post,
          userNickname: post.userNickname || '匿名用户',
          userAvatar: post.userAvatar || '/static/images/default-avatar.jpg',
          images: post.images || [],
          viewCount: post.viewCount || 0,
          likeCount: post.likeCount || 0,
          commentCount: post.commentCount || 0,
          isLiked: post.isLiked || false,
          isFavorited: post.isFavorited || false,
          createTime: this.formatCreateTime(post.createTime)
        }))
        
        this.posts = [...this.posts, ...formattedPosts]
        
        // 分配到左右列
        formattedPosts.forEach(post => {
          if (this.leftHeight <= this.rightHeight) {
            this.leftPosts.push(post)
            this.leftHeight += this.estimatePostHeight(post)
          } else {
            this.rightPosts.push(post)
            this.rightHeight += this.estimatePostHeight(post)
          }
        })
        
        // 加载状态
        this.loadMoreStatus = this.posts.length >= data.total ? 'noMore' : 'more'
      } catch (error) {
        console.error('加载帖子列表失败:', error)
        this.loadMoreStatus = 'more'
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    },
    
    // 格式化创建时间
    formatCreateTime(timeArray) {
      if (!timeArray || !Array.isArray(timeArray)) return ''
      const [year, month, day, hour, minute] = timeArray
      return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
    },
    
    // 估算帖子高度
    estimatePostHeight(post) {
      // 根据列宽计算图片高度
      const imageHeight = post.images && post.images.length > 0 ? this.columnWidth : 0
      
      // 标题行高
      const titleHeight = 48
      
      // 内容行高
      const contentLineHeight = 20
      const contentLines = Math.ceil((post.content || '').length / 15)
      const contentHeight = contentLines * contentLineHeight
      
      // 用户信息和底部操作栏高度
      const footerHeight = 88
      
      // 内边距
      const padding = 32
      
      return imageHeight + titleHeight + contentHeight + footerHeight + padding
    },
    
    // 图片加载完成
    onImageLoad(postId, event) {
      const post = this.posts.find(p => p.id === postId)
      if (post) {
        // 更新图片实际高度
        post.imageHeights.push(event.detail.height)
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      this.page = 1
      await this.loadPosts()
      this.isRefreshing = false
      uni.stopPullDownRefresh()
    },
    
    // 加载更多
    loadMore() {
      if (this.loadMoreStatus === 'more') {
        this.page++
        this.loadPosts()
      }
    },
    
    // 跳转到发布页
    goPost() {
      if (!isLoggedIn()) {
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return
      }
      
      uni.navigateTo({
        url: '/pages/community/post/index'
      })
    },
    
    // 跳转到详情页
    goDetail(post) {
      uni.navigateTo({
        url: `/pages/community/detail/index?id=${post.id}&userId=${post.userId}&userNickname=${encodeURIComponent(post.userNickname)}&userAvatar=${encodeURIComponent(post.userAvatar)}`
      })
    },
    
    // 跳转到搜索页
    goSearch() {
      uni.navigateTo({
        url: '/pages/community/search/index'
      })
    },
    
    // 跳转到用户空间
    goUserSpace(post) {
      if (post.userId) {
        uni.navigateTo({
          url: `/pages/community/user/index?userId=${post.userId}`
        })
      }
    },
    
    // 点赞帖子
    async handleLike(post) {
      if (!isLoggedIn()) {
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return
      }

      try {
        if (post.isLiked) {
          await this.$api.community.posts.unlike(post.id)
          post.isLiked = false
          post.likeCount--
        } else {
          await this.$api.community.posts.like(post.id)
          post.isLiked = true
          post.likeCount++
        }
      } catch (error) {
        console.error('点赞操作失败:', error)
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.community-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  padding-top: var(--status-bar-height);
  
  .nav-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    padding: 0 30rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
    
    .search-box {
      flex: 1;
      height: 64rpx;
      background: #f5f5f5;
      border-radius: 32rpx;
      margin: 0 20rpx;
      padding: 0 30rpx;
      display: flex;
      align-items: center;
      
      .placeholder {
        font-size: 28rpx;
        color: #999;
        margin-left: 10rpx;
      }
    }
    
    .post-btn {
      padding: 10rpx;
    }
  }
}

.content-scroll {
  margin-top: calc(var(--status-bar-height) + 88rpx);
  height: calc(100vh - var(--status-bar-height) - 88rpx);
}

.waterfall-container {
  display: flex;
  padding: 16rpx;
  box-sizing: border-box;
  background: #f8f8f8;
  gap: 16rpx;
}

.waterfall-column {
  flex: 1;
  min-width: 0; // 防止内容溢出
  
  .post-item {
    background-color: #fff;
    border-radius: 12rpx;
    margin-bottom: 16rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
    
    .image-wrap {
      position: relative;
      width: 100%;
      padding-bottom: 100%; // 1:1 宽高比
      background-color: #f8f8f8;
      overflow: hidden;
      
      .post-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .image-count {
        position: absolute;
        top: 12rpx;
        right: 12rpx;
        background: rgba(0, 0, 0, 0.3);
        padding: 4rpx 12rpx;
        border-radius: 20rpx;
        backdrop-filter: blur(4px);
        z-index: 1;
      }
    }
    
    .post-content {
      padding: 12rpx 16rpx;
      
      .title {
        font-size: 28rpx;
        color: #333;
        line-height: 1.4;
        font-weight: 500;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        margin-bottom: 8rpx;
      }
    }
    
    .post-footer {
      padding: 12rpx 16rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1px solid #f5f5f5;
      
      .user-info {
        flex: 1;
        display: flex;
        align-items: center;
        overflow: hidden;
        margin-right: 12rpx;
        
        .avatar {
          width: 36rpx;
          height: 36rpx;
          border-radius: 50%;
          margin-right: 8rpx;
          border: 1px solid #f5f5f5;
          flex-shrink: 0;
        }
        
        .nickname {
          font-size: 24rpx;
          color: #666;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      
      .like-info {
        display: flex;
        align-items: center;
        padding: 6rpx 12rpx;
        background: #f8f8f8;
        border-radius: 20rpx;
        flex-shrink: 0;
        
        text {
          font-size: 24rpx;
          color: #999;
          margin-left: 4rpx;
          
          &.active {
            color: #ff4757;
          }
        }
      }
    }
  }
}

// 响应式布局媒体查询
@media screen and (min-width: 768px) {
  .waterfall-container {
    padding: 20rpx;
    gap: 20rpx;
  }
  
  .post-item {
    margin-bottom: 20rpx;
    
    .post-content {
      padding: 16rpx 20rpx;
      
      .title {
        font-size: 30rpx;
      }
    }
    
    .post-footer {
      padding: 16rpx 20rpx;
      
      .avatar {
        width: 40rpx;
        height: 40rpx;
      }
      
      .nickname {
        font-size: 26rpx;
      }
    }
  }
}

@media screen and (max-width: 375px) {
  .waterfall-container {
    padding: 12rpx;
    gap: 12rpx;
  }
  
  .post-item {
    margin-bottom: 12rpx;
    
    .post-content {
      padding: 10rpx 12rpx;
      
      .title {
        font-size: 26rpx;
      }
    }
    
    .post-footer {
      padding: 10rpx 12rpx;
      
      .avatar {
        width: 32rpx;
        height: 32rpx;
      }
      
      .nickname {
        font-size: 22rpx;
      }
    }
  }
}
</style> 